<template>
  <div class="search-suggestion">
    <van-cell @click="onClick(item)" :title="item" icon="search" v-for="(item, index) in searchList" :key="index">
      <span slot="title" v-html="highlight(item)"></span>
    </van-cell>
  </div>
</template>

<script>
import { getTishi } from '@/api/search'
import { debounce } from 'lodash' // 按需引入体积小
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      searchList: []
    }
  },
  computed: {},
  watch: {
    searchText: {
      // debounce防抖
      handler: debounce(function (value) {
        console.log(this.searchText)
        this.search()
      }, 666),
      immediate: true // 立即侦听
    }
  },
  created () { },
  mounted () { },
  methods: {
    async search () {
      try {
        const { data: res } = await getTishi(this.searchText)
        // console.log(res.data)
        this.searchList = res.data.options
        console.log(this.searchList)
      } catch (err) {
        this.$toast.fail('获取联想建议失败')
      }
    },
    // 匹配文字红色高亮
    highlight (str) {
      var reg = new RegExp(this.searchText, 'gi') // 构造函数正则
      return str.replace(reg, '<span style="color:red;">' + this.searchText + '</span>')
    },
    onClick (str) {
      this.$emit('search-event', str)
    }
  }
}
</script>

<style scoped lang="less"></style>
